let connection = require("../dbutil/dbutil");
let myModule = require("./my-module");

function getInfo(id, token,callback) {
    let sql = "select * from user where uid = ? and token = ?";
    let sqlparams=[id, token]
    connection.query(sql, sqlparams, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            let ret = {
                code: 1002,
                user: result[0].username,
                uid: id,
                tel: result[0].tel,
                address: result[0].address,
                unpaid_order: 0,
                pending_order: 0,
                review_order: 0
            }
            if (result.length > 0 && myModule.verifyToken(token)) {
                let usql = "select * from personal_center where uid = '" + id + "'";
                connection.query(usql, function (err, result) {
                    if (err) {
                        console.log(err);
                    } else {
                        ret.code = 1001
                        if (result.length > 0) {
                            ret.tel = result[0].tel
                            ret.address = result[0].address
                            ret.unpaid_order = result[0].unpaid_order
                            ret.pending_order = result[0].pending_order
                            ret.review_order = result[0].review_order
                        }
                        callback(ret)
                    }
                })
            } else {
                callback(ret)
            }
        }
    })
}

function updateInfo(id, token, username, tel, address, callback) {
    let sql = "select * from user where uid = ? and token = ?";
    let sqlparams=[id, token]
    connection.query(sql, sqlparams, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            let ret = {
                code: 1002,
                msg: "更新失败"
            }
            if (result.length > 0 && myModule.verifyToken(token)) {
                let usql = "UPDATE user SET username = ?, tel = ?, address = ? WHERE uid = '" + result[0].uid + "'";
                let usqlparams=[username, tel, address]
                connection.query(usql, usqlparams, function (err, result) {
                    if (err) {
                        console.log(err);
                    } else {
                        ret.code = 1001
                        ret.msg = "更新成功"
                        callback(ret)
                    }
                })
            } else {
                callback(ret)
            }
        }
    })
}

exports.getInfo = getInfo;
exports.updateInfo = updateInfo;